package procsim;

public class TriState implements Element{
    private Signal cSig, inSig;
    private MSignal result;
    protected boolean inverted = false;
    public TriState(Signal in, Signal c){
        if(in!=null) in.addElement(this);
        if(c!=null) c.addElement(this);
        inSig=in;
        cSig=c;
    }
    @Override
    public TriState tick(){
        if(result==null || inSig==null) return this;
        if (cSig==null || (cSig!=null && cSig.isNull())) result.set(MSignal.HIGHZ);
        else{
            result.set(inSig.get());
            if(inverted) result.not();
        }
        return this;
    }
    @Override
    public MSignal result() {
        return result;
    }
    public TriState setResult(MSignal sig){
        result=sig;
        return this;
    }
    public TriState not(){
        inverted = Util.toggle(inverted);
        return this;
    }

    public boolean isInverted(){
        if(inverted) return true;
        else return false;
    }

    @Override
    public void updateSignal(Sig sig){
        boolean changed = false;
        if(inSig!=null && inSig==sig){
            inSig.set(sig.get(), false);
            changed = true;
        }
        if(cSig!=null && cSig==sig){
            cSig.set(sig.get(), false);
            changed = true;
        }
        if(changed) tick();
    }
}
